import pandas as pd
import os
import matplotlib.pyplot as plt
from kano_model import KanoModel



def read_data(file_path: str) -> pd.DataFrame:
    """读取数据文件，添加文件存在检查"""
    try:
        if not os.path.exists(file_path):
            print(f"错误：文件不存在 - {file_path}")
            return None
        data = pd.read_csv(file_path, sep='\t')
        print(f"成功读取数据：{len(data)} 条记录")
        return data
    except Exception as e:
        print(f"读取文件失败: {e}")
        return None

def save_plots(kano: KanoModel, output_dir: str) -> None:
    """保存可视化图表到指定目录"""
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
        print(f"创建目录: {output_dir}")
    
    for attr_name in kano.get_results().keys():
        plt.figure(figsize=(10, 6))
        kano.plot_kano_percentages(attr_name)
        plt.tight_layout()
        plt.savefig(os.path.join(output_dir, f"{attr_name}_kano_distribution.png"))
        plt.close()
    
    plt.figure(figsize=(12, 10))
    kano.plot_satisfaction_map()
    plt.tight_layout()
    plt.savefig(os.path.join(output_dir, "satisfaction_map.png"))
    plt.close()

def print_results(kano: KanoModel) -> None:
    """打印分析结果到命令行"""
    results = kano.get_results()
    print("\n" + "="*50)
    print("惠山泥人Kano模型分析结果")
    print("="*50)
    
    for attr, res in results.items():
        print(f"\n属性: {attr}")
        print(f"主导类别: {res['dominant_category']}")
        print("Kano类别分布:")
        for cat, pct in sorted(res['percentages'].items(), key=lambda x: -x[1]):
            print(f"  {cat}: {pct:.1f}%")
        print(f"满意度系数: {res['satisfaction']:.3f}")
        print(f"不满意度系数: {res['dissatisfaction']:.3f}")
    
    print("\n" + "="*50)
    print("属性优先级建议（基于满意度和不满意度系数）")
    print("="*50)
    sorted_attrs = sorted(results.items(), 
                         key=lambda x: x[1]['satisfaction'] * x[1]['dissatisfaction'], 
                         reverse=True)
    for i, (attr, _) in enumerate(sorted_attrs, 1):
        print(f"{i}. {attr}")

def save_kano_results(kano: KanoModel, output_dir: str) -> None:
    """将Kano分析结果保存到文本文件"""
    results = kano.get_results()
    output_path = os.path.join(output_dir, "kano_result.txt")
    
    with open(output_path, "w", encoding="utf-8") as f:
        f.write("="*50 + "\n")
        f.write("惠山泥人Kano模型分析结果\n")
        f.write("="*50 + "\n")
        
        for attr, res in results.items():
            f.write(f"\n属性: {attr}\n")
            f.write(f"主导类别: {res['dominant_category']}\n")
            f.write("Kano类别分布:\n")
            for cat, pct in sorted(res['percentages'].items(), key=lambda x: -x[1]):
                f.write(f"  {cat}: {pct:.1f}%\n")
            f.write(f"满意度系数: {res['satisfaction']:.3f}\n")
            f.write(f"不满意度系数: {res['dissatisfaction']:.3f}\n")
        
        f.write("\n" + "="*50 + "\n")
        f.write("属性优先级建议（基于满意度和不满意度系数）\n")
        f.write("="*50 + "\n")
        sorted_attrs = sorted(results.items(), 
                             key=lambda x: x[1]['satisfaction'] * x[1]['dissatisfaction'], 
                             reverse=True)
        for i, (attr, _) in enumerate(sorted_attrs, 1):
            f.write(f"{i}. {attr}\n")
    
    print(f"Kano分析结果已保存到 {output_path}")

def main():
    """主函数，针对惠山泥人场景调整属性"""
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    DATA_FILE = os.path.join(BASE_DIR, "data.txt")
    OUTPUT_DIR = os.path.join(BASE_DIR, "result")
    
    print(f"当前工作目录: {os.getcwd()}")
    print(f"脚本所在目录: {BASE_DIR}")
    print(f"数据文件路径: {DATA_FILE}")
    
    # 调整为惠山泥人相关属性对
    attribute_pairs = {
        '艺术价值': ('功能_艺术价值', 'dysfunction_艺术价值'),
        '文化传承': ('功能_文化传承', 'dysfunction_文化传承'),
        '工艺复杂度': ('功能_工艺复杂度', 'dysfunction_工艺复杂度'),
        '创新设计': ('功能_创新设计', 'dysfunction_创新设计'),
        '生产效率': ('功能_生产效率', 'dysfunction_生产效率'),
        '个性化程度': ('功能_个性化程度', 'dysfunction_个性化程度'),
        '成本': ('功能_成本', 'dysfunction_成本'),
        '市场接受度': ('功能_市场接受度', 'dysfunction_市场接受度')
    }
    
    data = read_data(DATA_FILE)
    if data is None:
        print("无法读取数据，程序退出。")
        return
    
    kano = KanoModel(data)
    kano.analyze(attribute_pairs)
    
    print_results(kano)
    save_plots(kano, OUTPUT_DIR)
    save_kano_results(kano, OUTPUT_DIR)
    print(f"\n可视化结果已保存到 {OUTPUT_DIR} 文件夹")

if __name__ == "__main__":
    main()